package mq

import (
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/streadway/amqp"
	"gopkg.in/yaml.v3"
)

type RabbitMQ struct {
	conn *amqp.Connection
	ch   *amqp.Channel
}

func ConsumeLogoutNotifications() {
	conn, err := amqp.Dial("amqp://guest:guest@localhost:5672/")
	if err != nil {
		log.Fatalf("RabbitMQ 连接失败: %v", err)
	}
	defer conn.Close()

	ch, err := conn.Channel()
	if err != nil {
		log.Fatalf("RabbitMQ 频道打开失败: %v", err)
	}
	defer ch.Close()

	msgs, err := ch.Consume("logout_queue", "", true, false, false, false, nil)
	if err != nil {
		log.Fatalf("RabbitMQ 消费失败: %v", err)
	}

	log.Println("监听用户登出事件")
	for msg := range msgs {
		var data map[string]string
		json.Unmarshal(msg.Body, &data)
		log.Printf("用户 %s 已登出，通知处理！", data["user_id"])
	}
}

type serverConfig struct {
	RabbitMQ RabbitMQConfig `yaml:"rabbitmq"`
}

type RabbitMQConfig struct {
	Host     string `yaml:"host"`
	Port     int    `yaml:"port"`
	User     string `yaml:"user"`
	Password string `yaml:"password"`
	Vhost    string `yaml:"vhost"`
}

func NewRabbitMQ(configPath string) *RabbitMQ {
	yamlFile, err := os.ReadFile(configPath)
	if err != nil {
		log.Fatalf("yaml文件读取失败: %v", err)
	}
	var serverConfig serverConfig
	err = yaml.Unmarshal(yamlFile, &serverConfig)
	if err != nil {
		log.Fatalf("yaml文件解析失败: %v", err)
	}
	conn, err := amqp.Dial(fmt.Sprintf("amqp://%s:%s@%s:%d/%s", serverConfig.RabbitMQ.User, serverConfig.RabbitMQ.Password, serverConfig.RabbitMQ.Host, serverConfig.RabbitMQ.Port, serverConfig.RabbitMQ.Vhost))
	if err != nil {
		log.Fatalf("RabbitMQ 连接失败: %v", err)
	}

	ch, err := conn.Channel()
	if err != nil {
		log.Fatalf("RabbitMQ 频道打开失败: %v", err)
	}

	return &RabbitMQ{
		conn: conn,
		ch:   ch,
	}
}
